<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 表格数据加载状态
const tableLoading = ref(false);

// 预约列表数据
const reservationList = ref([]);

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: '',
  reservationType: '',
  dateRange: []
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 预约状态选项
const reservationStatusOptions = [
  { label: '待确认', value: 'pending' },
  { label: '已确认', value: 'confirmed' },
  { label: '已完成', value: 'completed' },
  { label: '已取消', value: 'cancelled' },
  { label: '已改期', value: 'rescheduled' }
];

// 预约类型选项
const reservationTypeOptions = [
  { label: '桌台预约', value: 'table' },
  { label: '包厢预约', value: 'room' },
  { label: '活动预约', value: 'event' },
  { label: '其他预约', value: 'other' }
];

// 时间段选项
const timeSlotOptions = [
  { label: '上午场', value: 'morning', time: '09:00-12:00' },
  { label: '下午场', value: 'afternoon', time: '13:00-18:00' },
  { label: '晚间场', value: 'evening', time: '18:00-22:00' },
  { label: '全天场', value: 'fullday', time: '09:00-22:00' }
];

// 加载预约数据
const loadReservationData = () => {
  tableLoading.value = true;
  
  // 模拟API请求
  setTimeout(() => {
    // 生成模拟数据
    reservationList.value = Array.from({ length: 20 }, (_, index) => {
      const id = 'RES' + (10000 + index).toString();
      const statusIndex = Math.floor(Math.random() * 5);
      const typeIndex = Math.floor(Math.random() * 4);
      const timeSlotIndex = Math.floor(Math.random() * 4);
      const now = new Date();
      
      // 随机日期
      const reservationDate = new Date(now.getTime() + Math.floor(Math.random() * 30 - 10) * 24 * 60 * 60 * 1000);
      
      // 资源名称
      let resourceName = '';
      if (reservationTypeOptions[typeIndex].value === 'table') {
        resourceName = `${Math.floor(Math.random() * 50) + 1}号桌`;
      } else if (reservationTypeOptions[typeIndex].value === 'room') {
        resourceName = `${['A', 'B', 'C', 'D'][Math.floor(Math.random() * 4)]}${Math.floor(Math.random() * 10) + 1}包厢`;
      } else if (reservationTypeOptions[typeIndex].value === 'event') {
        resourceName = `${['周末', '会员', '节日', '特别'][Math.floor(Math.random() * 4)]}活动`;
      } else {
        resourceName = `其他预约项目`;
      }
      
      // 随机会员信息
      const memberName = `会员${Math.floor(Math.random() * 100) + 1}`;
      const memberPhone = `1381234${(Math.floor(Math.random() * 10000)).toString().padStart(4, '0')}`;
      
      return {
        id,
        reservationNo: id,
        memberName,
        memberPhone,
        reservationType: reservationTypeOptions[typeIndex].value,
        reservationTypeName: reservationTypeOptions[typeIndex].label,
        resourceName,
        reservationDate: reservationDate.toLocaleDateString(),
        timeSlot: timeSlotOptions[timeSlotIndex].value,
        timeSlotName: timeSlotOptions[timeSlotIndex].label,
        timeSlotTime: timeSlotOptions[timeSlotIndex].time,
        peopleCount: Math.floor(Math.random() * 10) + 1,
        status: reservationStatusOptions[statusIndex].value,
        statusName: reservationStatusOptions[statusIndex].label,
        createTime: new Date(now.getTime() - Math.floor(Math.random() * 10) * 24 * 60 * 60 * 1000).toLocaleString(),
        remark: Math.random() > 0.5 ? `备注信息${index + 1}` : ''
      };
    });
    
    pagination.total = 178; // 模拟总数据量
    tableLoading.value = false;
  }, 1000);
};

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  loadReservationData();
};

// 处理每页条数变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  loadReservationData();
};

// 处理查询
const handleSearch = () => {
  pagination.currentPage = 1;
  loadReservationData();
};

// 重置查询条件
const resetSearch = () => {
  searchForm.keyword = '';
  searchForm.status = '';
  searchForm.reservationType = '';
  searchForm.dateRange = [];
  
  pagination.currentPage = 1;
  loadReservationData();
};

// 查看预约详情
const viewReservationDetails = (row) => {
  ElMessage.info(`查看预约详情：${row.reservationNo}`);
};

// 确认预约
const confirmReservation = (row) => {
  if (row.status !== 'pending') {
    ElMessage.warning('只能确认待确认的预约');
    return;
  }
  
  ElMessageBox.confirm(`确定要确认预约"${row.reservationNo}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('确认成功');
    row.status = 'confirmed';
    row.statusName = '已确认';
  }).catch(() => {});
};

// 完成预约
const completeReservation = (row) => {
  if (row.status !== 'confirmed') {
    ElMessage.warning('只能完成已确认的预约');
    return;
  }
  
  ElMessageBox.confirm(`确定要标记预约"${row.reservationNo}"为已完成吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('操作成功');
    row.status = 'completed';
    row.statusName = '已完成';
  }).catch(() => {});
};

// 取消预约
const cancelReservation = (row) => {
  if (row.status === 'completed' || row.status === 'cancelled') {
    ElMessage.warning('已完成或已取消的预约不能取消');
    return;
  }
  
  ElMessageBox.confirm(`确定要取消预约"${row.reservationNo}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('取消成功');
    row.status = 'cancelled';
    row.statusName = '已取消';
  }).catch(() => {});
};

// 改期预约
const rescheduleReservation = (row) => {
  if (row.status === 'completed' || row.status === 'cancelled') {
    ElMessage.warning('已完成或已取消的预约不能改期');
    return;
  }
  
  ElMessage.info(`打开改期预约表单，预约号：${row.reservationNo}`);
};

// 删除预约
const deleteReservation = (row) => {
  if (row.status !== 'cancelled') {
    ElMessage.warning('只能删除已取消的预约');
    return;
  }
  
  ElMessageBox.confirm(`确定要删除预约"${row.reservationNo}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功');
    loadReservationData();
  }).catch(() => {});
};

// 初始化加载
onMounted(() => {
  loadReservationData();
});
</script>

<template>
  <div class="reservation-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>预约管理</h2>
    </div>
    
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="关键词">
          <el-input 
            v-model="searchForm.keyword" 
            placeholder="预约号/会员姓名/手机号"
            clearable
          />
        </el-form-item>
        <el-form-item label="预约状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option 
              v-for="item in reservationStatusOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预约类型">
          <el-select v-model="searchForm.reservationType" placeholder="请选择" clearable>
            <el-option 
              v-for="item in reservationTypeOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预约日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 表格区域 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>预约列表</span>
          <div>
            <el-button type="primary">
              <el-icon><Plus /></el-icon>
              新增预约
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="reservationList" 
        v-loading="tableLoading" 
        border 
        style="width: 100%"
      >
        <el-table-column prop="reservationNo" label="预约号" width="100" />
        <el-table-column prop="memberName" label="会员姓名" width="100" />
        <el-table-column prop="memberPhone" label="手机号" width="120" />
        <el-table-column prop="reservationTypeName" label="预约类型" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="
                row.reservationType === 'table' ? 'success' : 
                row.reservationType === 'room' ? 'warning' : 
                row.reservationType === 'event' ? 'primary' : 'info'
              "
            >
              {{ row.reservationTypeName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="resourceName" label="预约资源" width="120" />
        <el-table-column prop="reservationDate" label="预约日期" width="110" />
        <el-table-column label="时间段" width="140">
          <template #default="{ row }">
            {{ row.timeSlotName }} ({{ row.timeSlotTime }})
          </template>
        </el-table-column>
        <el-table-column prop="peopleCount" label="人数" width="80">
          <template #default="{ row }">
            {{ row.peopleCount }}人
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="
                row.status === 'pending' ? 'warning' : 
                row.status === 'confirmed' ? 'primary' : 
                row.status === 'completed' ? 'success' : 
                row.status === 'cancelled' ? 'info' : 'danger'
              "
            >
              {{ row.statusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="250">
          <template #default="{ row }">
            <el-button 
              size="small" 
              @click="viewReservationDetails(row)"
            >
              详情
            </el-button>
            <el-button 
              v-if="row.status === 'pending'"
              size="small" 
              type="primary" 
              @click="confirmReservation(row)"
            >
              确认
            </el-button>
            <el-button 
              v-if="row.status === 'confirmed'"
              size="small" 
              type="success" 
              @click="completeReservation(row)"
            >
              完成
            </el-button>
            <el-button 
              v-if="row.status !== 'completed' && row.status !== 'cancelled'"
              size="small" 
              type="warning" 
              @click="rescheduleReservation(row)"
            >
              改期
            </el-button>
            <el-button 
              v-if="row.status !== 'completed' && row.status !== 'cancelled'"
              size="small" 
              type="danger" 
              @click="cancelReservation(row)"
            >
              取消
            </el-button>
            <el-button 
              v-if="row.status === 'cancelled'"
              size="small" 
              type="danger" 
              @click="deleteReservation(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.reservation-container {
  padding: 20px;
}
.page-header {
  margin-bottom: 20px;
}
.search-card {
  margin-bottom: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 
